package com.bweab.util;


import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtil {
    //首先获取数据库链接数据源
    private  static DataSource dataSource;
    //在静态加载初始化
    static {
        //properties对象获取数据库连接
        Properties properties = new Properties();

        //储存数据库信息
        properties.put("driverClassName","com.mysql.cj.jdbc.Driver");
        properties.put("username","root");
        properties.put("password","root");
        properties.put("url","jdbc:mysql://192.168.56.10:3306/bweab_system");
        properties.put("initialSize","5");
        properties.put("maxActive","10");
        properties.put("maxWait","1000");
        //数据源
        try {
            dataSource = DruidDataSourceFactory.createDataSource(properties);//获取数据源
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    //创建获取数据库链接

    public static Connection getConnection()  {
        //创建Connection对象
        Connection connection=null;

        try {
            connection = dataSource.getConnection();//获取数据库连接
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("获取数据库连接");
        return connection;
    }


    //关闭数据库连接
    public static void closeConnection(Connection connection) throws SQLException {
        if(connection!=null){
                //关闭数据库连接
            try {
                //判断connection是否为空  如果为空则关闭 否则不执行

                    connection.close();
                    System.out.println("关闭数据库连接");
                }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    }

}
